<?php

class Default_UsuarioController extends Zend_Controller_Action {

    public function indexAction() {
        $this->view->breadcump1 = "Usuários";
        $this->view->breadcump2 = "Histórico";

        $log = new Application_Model_DbTable_Log();
        $select = $log->select()->where('controller = "'.$this->getRequest()->getControllerName().'"')->order("horario DESC")->limit(15);


        $this->view->log = $log->fetchAll($select);
    }

    public function novousuarioAction(){
        $form = new Benservi_Forms_Usuario();
        $usuario = new Application_Model_DbTable_Acesso();

        if($this->_request->isPost()){
            if ($form->isValid($this->_request->getPost())) {
                $data = $this->_request->getPost();
                unset($data['Salvar']);

                if($usuario->getEmailCadastrado($data['email']) == 0)
                {
                    $usuario->insert($data);
                    $this->view->success = "Usuário cadastrado com sucesso";
                }
                else{
                    $this->view->error = "Email ja cadastrado.";
                }

            }
        }

        $this->view->form = $form;
        $this->view->breadcump1 = "Usuários";
        $this->view->breadcump2 = "Novo Usuário";
    }

    public function listaAction() {
        $this->view->breadcump1 = "Usuários";
        $this->view->breadcump2 = "Lista";

        $usuario = new Application_Model_DbTable_Acesso();
        $select = $usuario->select()->where('nome <> "Gustavo Meredyk"');
        $this->view->usuario = $usuario->fetchAll($select);
    }


    public function removeAction() {
        $usuario = new Application_Model_DbTable_Acesso();
        
        if($this->_request->getParam('id') <> ''){
            $where = 'id = '.$this->_request->getParam('id');

            $select = $usuario->select()->where('id = '.$this->_request->getParam('id'));
            $usuarioRow = $usuario->fetchAll($select)->current();

            $usuario->delete($where);
            Benservi_Log_Log::factory("Usuário removida: ".$usuarioRow->nome, Zend_Log::INFO, $this->getRequest()->getControllerName());            
            $this->_redirect("/usuario/lista");            
        }
    }

    public function meusdadosAction() {
        $usuarioLog = Zend_Auth::getInstance()->setStorage(new Zend_Auth_Storage_Session("default"))->getStorage()->read();

        $usuario = new Application_Model_DbTable_Acesso();
        $select = $usuario->select()->where('id ='.$usuarioLog->id);
        $usuarioRow = $usuario->fetchAll($select)->current()->toArray();
        
        $form = new Benservi_Forms_MeusDados();        

        if($this->_request->isPost()){
            if ($form->isValid($this->_request->getPost())) {
                $data = $this->_request->getPost();
                unset($data["Salvar"]);

                if(sha1($data["oldPasswords"]) == $usuarioRow["passwords"]){
                   if($data["novoPasswords"] == $data["repetirPasswords"]) {
                        unset($data["repetirPasswords"]);
                        $data["passwords"] = $data["novoPasswords"];
                        unset($data["novoPasswords"]);
                        unset($data["oldPasswords"]);

                        if($data['email'] <> $usuarioLog->email){
                            if($usuario->getEmailCadastrado($data['email']) == 0)
                            {
                                $this->view->success = $this->atualizaDados($usuario,$usuarioLog,$data);
                            }
                            else{                                
                                $error = array();
                                $error["oldPasswords"] = array("error" => "Email ja cadastrado.");
                                $this->view->error = $error;
                            }
                        }
                        else{
                            $this->view->success = $this->atualizaDados($usuario,$usuarioLog,$data);
                        }
                    }
                    else{
                        $error = array();
                        $error["oldPasswords"] = array("error" => "Novo Password / Repetir Password não conferem");
                        $this->view->error = $error;
                    }
                }
                else{
                    $error = array();
                    $error["oldPasswords"] = array("error" => "Password Antigo esta incorreto");
                    $this->view->error = $error;
                }
            }
        }

        $form->populate($usuarioRow);
        
        $this->view->form = $form;

        $this->view->breadcump1 = "Usuários";
        $this->view->breadcump2 = "Meus Dados";
    }

    private function atualizaDados($usuario,$usuarioLog,$data)
    {
        //$usuario->insert($data);
        $where['id = ?'] = $usuarioLog->id;
        $usuario->update($data, $where);
       
        Benservi_Log_Log::factory("Alteração de cadastro", Zend_Log::INFO, $this->getRequest()->getControllerName());
        return "Cadastro atualizado com sucesso";
    }
}


